<?php
/**
 * Created by PhpStorm.
 * User: Dinh Thi
 * Date: 1/20/15
 * Time: 12:56 PM
 */

namespace MyApp\Application\Controller;

use DinhThi\MVC\Request;
use MyApp\Application\Model\UserModel;
use Zend\Authentication\AuthenticationService;

class UserController extends MyAppAbstractController {
    public function __construct(){
        parent::__construct();

    }

    public function indexAction(){

    }

    public function loginAction(){
        $user = new AuthenticationService();
        if ($user->hasIdentity()){
            $this->redirect('index');
        } else{
            $this->view->setTitle('Login');
            $this->view->redirect = Request::getInstance()->getParameter('redirect');
            $this->view->setLayout('login');
            $this->view->setTitle('Đăng nhập hệ thống', true);
            $this->view->render('user/login');
        }
    }

    public function logoutAction(){
        $model = new UserModel();
        $model->logout();
        $this->redirect('user', 'login');
    }

    /*==============================*/
    public function DoiMatKhauAction(){
        if (isset ($_POST['MatKhauCu'])){
            $user = new AuthenticationService();
            $userId = $user->getIdentity()->id;
            $MatKhauCu = $_POST['MatKhauCu'];

            $model = new UserModel();
            if ($model->KiemTraMatKhau($userId, $MatKhauCu)){
                $MatKhauMoi = $_POST['MatKhauMoi'];
                $model->DoiMatKhau($userId, $MatKhauMoi);
                echo 1;
            } else{
                echo 'Nhập sai mật khẩu cũ';
            }

        }
    }

    public function dologinAction(){
        $request = Request::getInstance();
        $redirect = $request->getPost('redirect');

        if ($request->getPost('username') != null){
            $user = new UserModel();

            $username = $request->getPost('username');
            $password = $request->getPost('password');

            $login = ($user->login($username, $password));
            if ($login->isValid()){
                $this->redirect('', '', null, $redirect);
            } else{
                if ($redirect != null)
                    $this->redirect('user', 'login', array('error' => 1, 'redirect' => urlencode($redirect)));
                else
                    $this->redirect('user','login', array('error' => 1));
            }
        } else{
            if ($redirect != null)
                $this->redirect('user', 'login', array('error' => 1, 'redirect' => urlencode($redirect)));
            else
                $this->redirect('user','login', array('error' => 1));
        }
    }
} 